package generate

import (
	"fmt"

	"github.com/golang/protobuf/protoc-gen-go/generator"

	c "gormx/conf"
)

var (
	DSNFormat = "%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local"
	DSNStr    = fmt.Sprintf(DSNFormat,
		c.Con.DBInfo.User,
		c.Con.DBInfo.Pwd,
		c.Con.DBInfo.Host,
		c.Con.DBInfo.Port,
		c.Con.DBInfo.DbName,
	)
)

// GenertateDbInfo 生成DB init的file
func GenertateDbInfo(tableNames []string) {

	if len(tableNames) == 0 {
		tables := getTables("")
		for _, table := range tables {
			tableNames = append(tableNames, table.Name)
		}
	}

	content := "package models\n\n"

	content += `
import (
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var (
	err       error
	Db        *gorm.DB
	DSNFormat = "%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local"
    DSNStr    = fmt.Sprintf(DSNFormat,
`
	content += fmt.Sprintf("\"%s\" ,", c.Con.DBInfo.User)
	content += fmt.Sprintf("\"%s\" ,", c.Con.DBInfo.Pwd)
	content += fmt.Sprintf("\"%s\" ,", c.Con.DBInfo.Host)
	content += fmt.Sprintf("\"%s\" ,", c.Con.DBInfo.Port)
	content += fmt.Sprintf("\"%s\"", c.Con.DBInfo.DbName)
	content += `	)
)`

	content += `
func init(){
		Db, err = gorm.Open(mysql.New(mysql.Config{
			DSN:                       DSNStr, // DSN data source name
			DefaultStringSize:         256,    // string 类型字段的默认长度
			DisableDatetimePrecision:  true,   // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
			DontSupportRenameIndex:    true,   // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
			DontSupportRenameColumn:   true,   // 用 "change" 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
			SkipInitializeWithVersion: false,  // 根据当前 MySQL 版本自动配置
		}), &gorm.Config{
			Logger: logger.New(
				log.New(os.Stdout,"\r",log.LstdFlags) ,
				logger.Config{
					SlowThreshold:             time.Second, // 慢 SQL 阈值
					LogLevel:                  logger.Info, // 日志级别
					IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
					Colorful:                  false,       // 禁用彩色打印
				},
			),
		})
		if err != nil {
			fmt.Println("连接数据库失败,err=", err)
			return
		}
		Db.Debug()
		sqlDB, _ := Db.DB()
		// SetMaxIdleConns 设置空闲连接池中连接的最大数量
		sqlDB.SetMaxIdleConns(10)
		// SetMaxOpenConns 设置打开数据库连接的最大数量。
		sqlDB.SetMaxOpenConns(100)
		// SetConnMaxLifetime 设置了连接可复用的最大时间。
		sqlDB.SetConnMaxLifetime(time.Hour)
		// 建立映射关系
		`
	if len(tableNames) != 0 {
		content += "Db.AutoMigrate(\n"
		for _, name := range tableNames {
			content += fmt.Sprintf("%s%s%s", "&", generator.CamelCase(name), "{},\n")
		}

		content += ")\n"
	}

	content += "go DbCheck()        "
	content += "}\n"

	content += `func DbCheck() {
	ticker := time.NewTicker(time.Duration(5) * time.Minute)
	defer ticker.Stop()

	for range ticker.C {
		sqlDB, err := Db.DB()
		if err != nil {
			fmt.Printf("获取数据库对象失败: %v\n", err)
			continue
		}
		if err := sqlDB.Ping(); err != nil {
			fmt.Printf("ping 数据库失败: %v\n", err)
			continue
		}
		fmt.Println("ping 数据库成功")
	}
}
	
	`

	makeFile(content, "dbUtil")
	fmt.Println("db utils" + " 已生成...")
}
